<?php
/**
 *   OPENSHOP     Supply Chain Management,SCM
 * 
 *   @link        http://baison.com.cn
 *   @copyright   Baison, Inc.
 *   @package     OpenShop
 *   @version     $Id: scm_depot.php,v 1.0 2009/07/13 09:36:58 created $
 *   @author      FillBag <fillbag@hotmail.com>
 */

define('IN_OS', true);
require(dirname(__FILE__) . '/includes/init.php');
require(dirname(__FILE__) . '/includes/lib_scm.php');

$exc_check 			= 	new exchange($os->table('scm_check_order'), $db, 'order_id', 'order_sn');
$exc_loss 			= 	new exchange($os->table('scm_loss_order'), $db, 'order_id', 'order_sn');

$action 			= 	isset($_REQUEST['act']) ? $_REQUEST['act'] : 'list_check_order';

if($_REQUEST['act']=='list_check_order'){
     /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '仓储盘点单列表');   
	$smarty->assign('action_link',  array('text' => '添加仓储盘点单', 'href' => 'scm_depot.php?act=add_check_order'));      
    $smarty->assign('full_page',    1);
    
    clear_tmp_scm_order('check');
    
    $list = scm_check_order_list();  
    $smarty->assign('status_list', 	            scm_order_status('check'));    
    $smarty->assign('order_list', 	            $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_check_order_list.tpl');		
}

elseif($_REQUEST['act']=='query_check_order'){
	
    $list = scm_check_order_list();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
    $smarty->assign('page_count',     		   $list['page_count']);
    
    make_json_result($smarty->fetch('scm_check_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  	
}

elseif($_REQUEST['act']=='info_check_order'){
	
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);

    $smarty->assign('ur_here', '查看仓储盘点单');
    $smarty->assign('action_link', array('href' => 'scm_depot.php?act=list_check_order', 'text' => '仓储盘点单列表'));	  
        
    $order = scm_check_order_info($order_id);
	if (empty($order))
	{
		die('仓储盘点单不存在');
	}
	
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_check_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_check_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql)); 
    
	$smarty->assign('order', $order);
	
	$goods_list = scm_order_goods('check', $order_id);	
	$smarty->assign('goods_list', $goods_list);
		
	$smarty->assign('action_list', scm_order_action('check', $order_id));
	
    assign_query_info();      	
    $smarty->display('scm_check_order_info.tpl');     
}

elseif($_REQUEST['act']=='add_check_order' || $_REQUEST['act']=='edit_check_order'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_check_order';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_check_order' : 'edit_scm_check_order';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_check_order' : 'update_check_order');

    /* 初始化、取得仓储盘点单信息 */
    if ($is_add)
    {
    	clear_tmp_scm_order('check');
        $order = array(
            'order_sn'   	            => create_fast_order_sn('check'),
            'add_time'                  => gmtime()
        );  
        $order_id     = create_tmp_scm_order('check', $order);
        $order = scm_check_order_info($order_id);
        if (empty($order))
        {
            sys_msg('仓储盘点单不存在');
        }  
        
	    /* 清除缓存 */
	    clear_cache_files();

	 	os_header("Location: scm_depot.php?act=edit_check_goods&is_temp=1&id=$order_id");
		exit;           
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = intval($_GET['id']);
        $order = scm_check_order_info($id);
        if (empty($order) || ($order['order_status']<>0))
        {
            sys_msg('仓储盘点单不存在或状态无效');
        }
    }    

    $smarty->assign('order', $order);


    /* 显示模板 */
    if (!$is_add)
    {
        $smarty->assign('ur_here', '编辑仓储盘点单');
    }
    if (!$is_add)
    {
        $href = 'scm_depot.php?act=list_check_order&' . list_link_postfix();
    }
    $smarty->assign('action_link', array('href' => $href, 'text' => '仓储盘点单列表'));
    
    assign_query_info();    
    $smarty->display('scm_check_order_edit.tpl');	
}


elseif($_REQUEST['act']=='insert_check_order' || $_REQUEST['act']=='update_check_order'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'insert_check_order';
    /* 权限检查 */
    
    $priv_str = $is_add ? 'add_scm_check_order' : 'edit_scm_check_order';
    admin_priv($priv_str);

    /* 提交值 */
    $order = array(
        'order_id'     			            => intval($_POST['id']),
        'order_sn'   		                => sub_str($_POST['order_sn'], 60, false),
		'depot_id'   			        	=> 0,
		'seat_id'      				        => 0,
		'order_brief'    				    => trim($_POST['order_brief']),
		'add_time'         					=> local_strtotime($_POST['add_time']),
		'is_temp'                           => 0
    );

    /* 判断单据编号是否重复 */
    if (!$exc_check->is_only('order_sn', $order['order_sn'], $order['order_id']))
    {
        sys_msg('该单据编号已存在，请您换一个编号');
    }

    /* 保存采购订单信息 */
    if (!$is_add)
    {
        $db->autoExecute($os->table('scm_check_order'), $order, 'UPDATE', "order_id = '$order[order_id]'");
    }

    /* 记日志 */
    if (!$is_add)
    {
        admin_log('仓储盘点单, 单号 ' . $order['order_sn'], 'edit', 'scm_check_order');
    }

    /* 清除缓存 */
    clear_cache_files();

    $links = array(
        array('href' => "scm_depot.php?act=info_check_order&id=$order[order_id]", 'text' => '查看仓储盘点单'),
        array('href' => "scm_depot.php?act=list_check_order", 'text' => '返回仓储盘点单列表'),
        array('href' => "scm_depot.php?act=add_check_order", 'text' => '添加仓储盘点单')
    );
    sys_msg('生成仓储盘点单成功', 0, $links);
	exit;	
}

elseif($_REQUEST['act']=='remove_check_order'){	

    check_authz_json('drop_scm_check_order');

    $order_id = intval($_GET['id']);
    $order = scm_check_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	if($_REQUEST['is_ajax']==1){
    		make_json_error('仓储盘点单不存在或状态无效');
    	}else{
    		sys_msg('仓储盘点单不存在或状态无效');
    	}
    	exit;
    }
    if($db->query("DELETE FROM " . $os->table('scm_check_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('仓储盘点单 s%', $order['order_sn']), 'remove', 'scm_check_order');	
	    $db->query("DELETE FROM " . $os->table('scm_check_goods') . " WHERE order_id='$order_id'");
    }

    /* 清除缓存 */
    clear_cache_files();
    if($_REQUEST['is_ajax']==1){
    	$url = 'scm_depot.php?act=query_check_order&' . str_replace('act=remove_check_order', '', $_SERVER['QUERY_STRING']);
    }else{
    	$url = 'scm_depot.php?act=list_check_order';
    }
    os_header("Location: $url\n");
    exit;		
}

elseif($_REQUEST['act']=='edit_check_goods'){	
    /* 检查权限 */
//    admin_priv();  
      
    if(empty($_GET['id']))
    {
    	sys_msg('invalid param');
    }    
    
    $order_id     = intval($_GET['id']);
    $order        = scm_check_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg('仓储盘点单不存在或状态无效');
    }   
    $smarty->assign('ur_here', '编辑仓储盘点单商品');
    $smarty->assign('action_link', array('href' => 'scm_depot.php?act=list_check_order', 'text' => '仓储盘点单列表'));	  
     
	$smarty->assign('order', $order);   
	
	$goods_list = scm_order_goods('check', $order_id);
    $smarty->assign('goods_list', $goods_list);
             
    assign_query_info();
    $smarty->display('scm_check_goods_edit.tpl');
}

elseif($_REQUEST['act']=='edit_post_check_goods'){
    if(empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }
    if(empty($_POST['ext_act']) && empty($_POST['goodslist'])){
    	sys_msg('invalid param');
    }
    $is_temp      =  !empty($_POST['is_temp']) ? intval($_POST['is_temp']) : 0;
    $order_id     = intval($_POST['order_id']);
    $order        = scm_check_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg('仓储盘点单不存在或状态无效');
    }
    
    if($_POST['ext_act']=='barcode_to_order'){
    	$type_barcode  = intval($_POST['type_barcode']);
    	$goods_number  = intval($_POST['goods_number']);
    	$goods_barcode = trim($_POST['goods_barcode']);

    	$sql = "SELECT goods_id,color_id,size_id FROM ".$os->table('goods_barcode')." WHERE barcode='$goods_barcode'";
    	$row = $db->getRow($sql);
    	if(!empty($row)){
    		$goods_nums[$row['goods_id']][$row['color_id']][$row['size_id']] = $goods_number;    		
    	}else{
	    	$identify_schemes = get_barcode_identify_schemes(); 
	    	$goods_nums = get_barcode_identify_goods($identify_schemes, $goods_barcode, $goods_number);    		
    	}
    }else{
    	$goods_nums = $_POST['goods_nums'];
    }

    edit_scm_depot_order_goods('check', $order_id, $goods_nums);	
   
    $order_stat = scm_order_amount('check', $order_id);
    /* 更新商品总金额和订单总金额 */
    update_scm_order('check', $order_id, array('goods_number' => $order_stat['goods_number'], 
    										   'order_amount' => $order_stat['order_amount']));
    /* todo 记录日志 */
    $sn = $order['order_sn'];
    $sn .= ",总数量:$order_stat[goods_number],总金额:$order_stat[order_amount]";
    admin_log($sn, 'edit', 'scm_check_goods');

    /* 跳回订单商品 */
    os_header("Location: scm_depot.php?act=edit_check_goods&is_temp=$is_temp&id=$order_id");
    exit;
}

elseif($_REQUEST['act']=='update_post_check_goods'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }
    $is_temp      =  !empty($_POST['is_temp']) ? intval($_POST['is_temp']) : 0;
    $order_id     = intval($_POST['order_id']);
    $order        = scm_check_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg('仓储盘点单不存在或状态无效');
    }	
    update_scm_depot_order_goods('check', $order_id, $_POST);  
    
    $order_stat = scm_order_amount('check', $order_id);
    /* 更新商品总金额和订单总金额 */
    update_scm_order('check', $order_id, array('goods_number' => $order_stat['goods_number'], 
    										   'order_amount' => $order_stat['order_amount']));
    /* todo 记录日志 */
    $sn = $order['order_sn'];
    $sn .= ",总数量:$order_stat[goods_number],总金额:$order_stat[order_amount]";
    admin_log($sn, 'edit', 'scm_check_goods');

    /* 跳回订单商品 */
    os_header("Location: scm_depot.php?act=edit_check_goods&is_temp=$is_temp&id=$order_id");
    exit;	
}
/*------------------------------------------------------ */
//-- 删除单据商品
/*------------------------------------------------------ */
elseif($_REQUEST['act']=='remove_check_goods'){
	if(empty($_GET['order_id'])){
        sys_msg('invalid param');			
	}
	$is_temp      =  !empty($_GET['is_temp']) ? intval($_GET['is_temp']) : 0;
    $order_id     = intval($_GET['order_id']);
    $order        = scm_check_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg('仓储盘点单不存在或状态无效');
    }  
	
	if(empty($_GET['goods_id']) && empty($_GET['rec_id'])){
        sys_msg('invalid param');		
	}	
	if(!empty($_GET['rec_id']) && $_GET['rec_id']>0){
		$db->query("DELETE FROM " . $os->table('scm_check_goods') . " WHERE rec_id=" . intval($_GET['rec_id']));
	}else{
		$db->query("DELETE FROM " . $os->table('scm_check_goods') . " WHERE order_id=$order_id AND goods_id=" . intval($_GET['goods_id']));
	}

    $order_stat = scm_order_amount('check', $order_id);
    /* 更新商品总金额和订单总金额 */
    update_scm_order('check', $order_id, array('goods_number' => $order_stat['goods_number'], 
    										   'order_amount' => $order_stat['order_amount']));
   	$sn = $order['order_sn'];
    admin_log($sn, 'remove', 'scm_check_goods'); 										 
    /* 跳回订单商品 */
    os_header("Location: scm_depot.php?act=edit_check_goods&is_temp=$is_temp&id=$order_id");
    exit;		
}

elseif($_REQUEST['act']=='operate_check_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_POST['order_id']);
    $order = scm_check_order_info($order_id);
    if(empty($order)){
		sys_msg('仓储盘点单不存在');
    }
    
	if($order['goods_number']<=0){
		sys_msg('仓储盘点单没有商品不能做任何操作');		
	}
	$update_ext  = array();
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);
	$goto_act = "info_check_order&id=$order_id";

    if (isset($_POST['confirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法确认通过');
    	}
        $operation      = 'order_status';
        $order_status   = 1;
    }

    if(isset($_POST['disaffirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法作废');
    	}
        $operation      = 'order_status';
        $order_status   = 2;
    }  
    
    if(isset($_POST['loss'])){
	    if($order['order_status'] <> 1 ||  $order['loss_order_id'] > 0){
	    	sys_msg('无效状态无法生成盈亏单');	
	    }
	    
	    $order_sn = create_fast_order_sn('loss');
	    
	    $loss_order_id = create_scm_loss_order($order_id, $order_sn);   
	    create_scm_loss_goods($loss_order_id, $order_id);
	    $sql_num = "SELECT SUM(goods_number_loss) number_loss, SUM(actual_price*goods_number_loss) amount_loss FROM " . 
	               $os->table('scm_loss_goods') . " WHERE order_id=$loss_order_id";
	    $order_stat = $db->getRow($sql_num);
	    update_scm_order('loss', $loss_order_id, array('goods_number_loss'=>$order_stat['number_loss'],
	                                                   'order_amount_loss'=>$order_stat['amount_loss']));
	    $update_ext     = array('loss_order_id'=>$loss_order_id);
        $operation      = 'order_status';
        $order_status   = 3;
	    $goto_act       = "info_loss_order&id=$loss_order_id";
    }
        
    update_scm_order('check', $order_id, array_merge(array($operation => $order_status), $update_ext));
    update_scm_order_action('check', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm_depot.php?act=$goto_act");
    exit;		
}

elseif($_REQUEST['act']=='list_loss_order'){
     /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '仓储盈亏单列表');     
    $smarty->assign('full_page',    1);
    
    $list = scm_loss_order_list();  
    $smarty->assign('status_list', 	            scm_order_status('loss'));    
    $smarty->assign('order_list', 	            $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_loss_order_list.tpl');		
}

elseif($_REQUEST['act']=='query_loss_order'){
	
    $list = scm_loss_order_list();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
    $smarty->assign('page_count',     		   $list['page_count']);
    
    make_json_result($smarty->fetch('scm_loss_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  	
}

elseif($_REQUEST['act']=='info_loss_order'){
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);

    $smarty->assign('ur_here', '查看仓储盈亏单');
    $smarty->assign('action_link', array('href' => 'scm_depot.php?act=list_loss_order', 'text' => '仓储盈亏单列表'));	  
    $order = scm_loss_order_info($order_id);
	if (empty($order))
	{
		die('仓储盈亏单不存在');
	}
	
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_loss_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_loss_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql)); 
    
	$smarty->assign('order', $order);
	
	$goods_list = scm_loss_goods('loss', $order_id);
	
	$smarty->assign('goods_list', $goods_list);
		
	$smarty->assign('action_list', scm_order_action('loss', $order_id));
	
    assign_query_info();        	 
    $smarty->display('scm_loss_order_info.tpl');	
}

elseif($_REQUEST['act']=='edit_loss_order'){

    admin_priv('edit_scm_loss_order');
    
    $smarty->assign('form_action', 'update_loss_order');

    /* 初始化、取得仓储盈亏单信息 */
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }

    $id = intval($_GET['id']);
    $order = scm_loss_order_info($id);
    if (empty($order))
    {
        sys_msg('仓储盈亏单不存在');
    }

    $smarty->assign('order', $order);


    /* 显示模板 */
    $smarty->assign('ur_here', '编辑仓储盈亏单');

    $href = 'scm_depot.php?act=list_loss_order&' . list_link_postfix();

    $smarty->assign('action_link', array('href' => $href, 'text' => '仓储盈亏单列表'));
    
    assign_query_info();
    
    $smarty->display('scm_loss_order_edit.tpl');	
}

elseif($_REQUEST['act']=='update_loss_order'){
	
    admin_priv('edit_scm_loss_order');

    /* 提交值 */
    $order = array(
        'order_id'     			            => intval($_POST['id']),
        'order_sn'   		                => sub_str($_POST['order_sn'], 60, false),
		'order_brief'    				    => trim($_POST['order_brief']),
		'add_time'         					=> local_strtotime($_POST['add_time'])
    );
    /* 判断单据编号是否重复 */
    if (!$exc_loss->is_only('order_sn', $order['order_sn'], $order['order_id']))
    {
        sys_msg('该单据编号已存在，请您换一个编号');
    }   
    
    /* 保存仓储盈亏单信息 */
    $db->autoExecute($os->table('scm_loss_order'), $order, 'UPDATE', "order_id = '$order[order_id]'");
    
    admin_log('仓储盈亏单, 单号 ' . $order['order_sn'], 'edit', 'scm_loss_order');

    /* 清除缓存 */
    clear_cache_files();

 	os_header("Location: scm_depot.php?act=info_loss_order&id=$order[order_id]");
	exit;	
}

elseif($_REQUEST['act']=='remove_loss_order'){
    check_authz_json('drop_scm_loss_order');

    $order_id = intval($_GET['id']);
    $order = scm_loss_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
     	if($_REQUEST['is_ajax']==1){
    		make_json_error('仓储盈亏单不存在或状态无效');
    	}else{
    		sys_msg('仓储盈亏单不存在或状态无效');
    	}
    	exit;
    }
    if($db->query("DELETE FROM " . $os->table('scm_loss_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('仓储盈亏单 s%', $order['order_sn']), 'remove', 'scm_loss_order');	
	    $db->query("DELETE FROM " . $os->table('scm_loss_goods') . " WHERE order_id='$order_id'");   
    }

    /* 清除缓存 */
    clear_cache_files();
    
	if($_REQUEST['is_ajax']==1){
    	$url = 'scm_depot.php?act=query_loss_order&' . str_replace('act=remove_loss_order', '', $_SERVER['QUERY_STRING']);
	}else{
		$url = 'scm_depot.php?act=list_loss_order';
	}
    os_header("Location: $url\n");
    exit;
}

elseif($_REQUEST['act']=='operate_loss_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id   = intval($_POST['order_id']);
    $order = scm_loss_order_info($order_id);
    if(empty($order)){
		sys_msg('仓储盈亏单不存在');
    }
   	if($order['goods_number']<=0){
		sys_msg('仓储盈亏单没有商品不能做任何操作');		
	} 
	$update_ext = array();
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);
	$goto_act       = "info_loss_order&id=$order_id";
	
    if (isset($_POST['confirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法确认通过');
    	}
        $operation      = 'order_status';
        $order_status   = 1;
    }

    if (isset($_POST['disaffirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法作废');
    	}
        $operation      = 'order_status';
        $order_status   = 2;
    }
    
    if(isset($_POST['rectify'])){
	    if($order['order_status'] <> 1 ||  $order['rectify_order_id'] > 0){
	    	sys_msg('无效状态无法生成调整单');	
	    }
	    
	    $order_sn = create_fast_order_sn('rectify');
	    
	    $rectify_order_id = create_scm_rectify_order($order_id, $order_sn);   
	    create_scm_rectify_goods($rectify_order_id, $order_id);
	    $update_ext     = array('rectify_order_id'=>$rectify_order_id);
        $operation      = 'order_status';
        $order_status   = 3;
		$goto_act       = "info_rectify_order&id=$rectify_order_id";
    }
    
    update_scm_order('loss', $order_id, array_merge(array($operation => $order_status), $update_ext));
	update_scm_order_action('loss', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm_depot.php?act=$goto_act");
    exit;
}

elseif($_REQUEST['act']=='list_rectify_order'){
     /* 检查权限 */
    admin_priv();    
    
    $smarty->assign('ur_here',      '仓储调整单列表');   
    $smarty->assign('full_page',    1);
    clear_tmp_scm_order('rectify'); 
    
    $list = scm_rectify_order_list();  
    $smarty->assign('status_list', 	            scm_order_status('rectify'));    
    $smarty->assign('order_list', 	            $list['item']);    
    $smarty->assign('filter',        		    $list['filter']);
    $smarty->assign('page_count',    		    $list['page_count']); 
    $smarty->assign('record_count',  		    $list['record_count']);
    
    assign_query_info();
    $smarty->display('scm_rectify_order_list.tpl');		
}

elseif($_REQUEST['act']=='query_rectify_order'){
	
    $list = scm_rectify_order_list();
    $smarty->assign('order_list',              $list['item']);
    $smarty->assign('filter',         		   $list['filter']);
    $smarty->assign('record_count',   		   $list['record_count']);
    $smarty->assign('page_count',     		   $list['page_count']);
    
    make_json_result($smarty->fetch('scm_rectify_order_list.tpl'), '',
        array('filter' => $list['filter'], 'page_count' => $list['page_count']));  	
}

elseif($_REQUEST['act']=='info_rectify_order'){
    if (empty($_GET['id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_GET['id']);

    $smarty->assign('ur_here', '查看仓储调整单');
    $smarty->assign('action_link', array('href' => 'scm_depot.php?act=list_rectify_order', 'text' => '仓储调整单列表'));	  
        
    $order = scm_rectify_order_info($order_id);
	if (empty($order))
	{
		die('仓储调整单不存在');
	}
	
    $sql = "SELECT MAX(order_id) FROM " . $os->table('scm_rectify_order') . " WHERE order_id < '$order[order_id]'";    
    $smarty->assign('prev_id', $db->getOne($sql));
    $sql = "SELECT MIN(order_id) FROM " . $os->table('scm_rectify_order') . " WHERE order_id > '$order[order_id]'";
    $smarty->assign('next_id', $db->getOne($sql)); 
    
	$smarty->assign('order', $order);
	
	$goods_list = scm_loss_goods('rectify', $order_id);
	
	$smarty->assign('goods_list', $goods_list);
		
	$smarty->assign('action_list', scm_order_action('rectify', $order_id));
	
    assign_query_info();        	 
    $smarty->display('scm_rectify_order_info.tpl');	
}

elseif($_REQUEST['act']=='add_rectify_order' || $_REQUEST['act']=='edit_rectify_order'){
    /* 是否添加 */
    $is_add = $_REQUEST['act'] == 'add_rectify_order';
    /* 权限检查 */
    $priv_str = $is_add ? 'add_scm_rectify_order' : 'edit_scm_rectify_order';
    admin_priv($priv_str);
    
    $smarty->assign('form_action', $is_add ? 'insert_rectify_order' : 'update_rectify_order');

    /* 初始化、取得仓储调整单信息 */
    if ($is_add)
    {
    	clear_tmp_scm_order('rectify');
        $order = array(
            'order_sn'   	            => create_fast_order_sn('rectify'),
            'add_time'                  => gmtime()
        );  
        $order_id     = create_tmp_scm_order('rectify', $order);
        $order        = scm_rectify_order_info($order_id);
        if (empty($order))
        {
            sys_msg('仓储调整单不存在');
        }  
        
	    /* 清除缓存 */
	    clear_cache_files();
	    
	 	os_header("Location: scm_depot.php?act=edit_rectify_goods&is_temp=1&id=$order_id");
		exit;           
    }
    else
    {
        if (empty($_GET['id']))
        {
            sys_msg('invalid param');
        }

        $id = intval($_GET['id']);
        $order = scm_rectify_order_info($id);
        if (empty($order) || ($order['order_status']<>0))
        {
            sys_msg('仓储调整单或状态无效');
        }    	
    }

    $smarty->assign('order', $order);

    /* 显示模板 */
    if (!$is_add)
    {
        $smarty->assign('ur_here', '编辑仓储调整单');
    }
    if (!$is_add)
    {
        $href = 'scm_depot.php?act=list_rectify_order&' . list_link_postfix();
    }

    $smarty->assign('action_link', array('href' => $href, 'text' => '仓储调整单列表'));
    
    assign_query_info();    
    $smarty->display('scm_rectify_order_edit.tpl');	
}

elseif($_REQUEST['act']=='update_rectify_order'){
	
    admin_priv('edit_scm_rectify_order');
    /* 提交值 */
    $order = array(
        'order_id'     			            => intval($_POST['id']),
        'order_sn'   		                => sub_str($_POST['order_sn'], 60, false),
		'depot_id'   			        	=> 0,
		'seat_id'      				        => 0,
		'order_brief'    				    => trim($_POST['order_brief']),
		'is_freedom'                        => 1,
		'add_time'         					=> local_strtotime($_POST['add_time']),
		'is_temp'                           => 0
    );
    /* 判断单据编号是否重复 */
    if (!$exc_loss->is_only('order_sn', $order['order_sn'], $order['order_id']))
    {
        sys_msg('该单据编号已存在，请您换一个编号');
    }   
    
    /* 保存仓储调整单信息 */
    $db->autoExecute($os->table('scm_rectify_order'), $order, 'UPDATE', "order_id = '$order[order_id]'");
    
    admin_log('仓储调整单, 单号 ' . $order['order_sn'], 'edit', 'scm_rectify_order');

    /* 清除缓存 */
    clear_cache_files();

 	os_header("Location: scm_depot.php?act=info_rectify_order&id=$order[order_id]");
	exit;	
}

elseif($_REQUEST['act']=='edit_rectify_goods'){
    /* 检查权限 */
//    admin_priv();  
      
    if(empty($_GET['id']))
    {
    	sys_msg('invalid param');
    }    
    
    $order_id     = intval($_GET['id']);
    $order        = scm_rectify_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
    	sys_msg('仓储调整单不存在或状态无效');
    }   
    $smarty->assign('ur_here', '编辑仓储调整单商品');
    $smarty->assign('action_link', array('href' => 'scm_depot.php?act=list_rectify_order', 'text' => '仓储调整单列表'));	  
     
	$smarty->assign('order', $order);   
	
	$goods_list = scm_loss_goods('rectify', $order_id);
    $smarty->assign('goods_list', $goods_list);
             
    assign_query_info();
    $smarty->display('scm_rectify_goods_edit.tpl');	
}

elseif($_REQUEST['act']=='edit_post_rectify_goods'){
    if(empty($_POST['order_id']) || empty($_POST['goodslist']))
    {
        sys_msg('invalid param');
    }
    $order_id     = intval($_POST['order_id']);
    $order        = scm_rectify_order_info($order_id);
    if(empty($order)){
    	sys_msg('仓储调整单不存在或状态无效');
    }

    edit_scm_depot_order_goods('rectify', $order_id, $_POST['goods_nums']);	
    $order_stat1 = scm_order_amount('rectify', $order_id);
    $sql_num = "SELECT SUM(goods_number_loss) number_loss, SUM(actual_price*goods_number_loss) amount_loss FROM " . 
               $os->table('scm_rectify_goods') . " WHERE order_id=$order_id";
    $order_stat2 = $db->getRow($sql_num);
    
    /* 更新商品总金额和订单总金额 */
    update_scm_order('rectify', $order_id, array('goods_number'      => $order_stat1['goods_number'],
                                                 'order_amount'      => $order_stat1['order_amount'],
                                                 'goods_number_loss' => $order_stat2['number_loss'],
                                                 'order_amount_loss' => $order_stat2['amount_loss']));
    /* todo 记录日志 */
    $sn = $order['order_sn'];
    $sn .= ",总数量:$order_stat[goods_number],总金额:$order_stat[order_amount]";
    admin_log($sn, 'edit', 'scm_rectify_goods');

    /* 跳回订单商品 */
    os_header("Location: scm_depot.php?act=edit_rectify_goods&id=$order_id");
    exit;	
}

elseif($_REQUEST['act']=='update_post_rectify_goods'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }
    $order_id     = intval($_POST['order_id']);
    $order        = scm_rectify_order_info($order_id);
    if(empty($order)){
    	sys_msg('仓储调整单不存在或状态无效');
    }	
    update_scm_depot_order_goods('rectify', $order_id, $_POST);  
    
    $order_stat1 = scm_order_amount('rectify', $order_id);
    $sql_num = "SELECT SUM(goods_number_loss) number_loss, SUM(actual_price*goods_number_loss) amount_loss FROM " . 
               $os->table('scm_rectify_goods') . " WHERE order_id=$order_id";
    $order_stat2 = $db->getRow($sql_num);
    
    /* 更新商品总金额和订单总金额 */
    update_scm_order('rectify', $order_id, array('goods_number'      => $order_stat1['goods_number'],
                                                 'order_amount'      => $order_stat1['order_amount'],
                                                 'goods_number_loss' => $order_stat2['number_loss'],
                                                 'order_amount_loss' => $order_stat2['amount_loss']));
    /* todo 记录日志 */
    $sn = $order['order_sn'];
    $sn .= ",总数量:$order_stat[goods_number],总金额:$order_stat[order_amount]";
    admin_log($sn, 'edit', 'scm_rectify_goods');

    /* 跳回订单商品 */
    os_header("Location: scm_depot.php?act=edit_rectify_goods&id=$order_id");
    exit;	
}

elseif($_REQUEST['act']=='remove_rectify_order'){
    check_authz_json('drop_scm_rectify_order');

    $order_id = intval($_GET['id']);
    $order = scm_rectify_order_info($order_id);
    if(empty($order) || ($order['order_status'] <> 0)){
     	if($_REQUEST['is_ajax']==1){
    		make_json_error('仓储调整单不存在或状态无效');
    	}else{
    		sys_msg('仓储调整单不存在或状态无效');
    	}
    	exit;
    }
    
    if($db->query("DELETE FROM " . $os->table('scm_rectify_order') . " WHERE order_id='$order_id'")){
	    /* 记日志 */
	    admin_log(sprintf('仓储调整单 s%', $order['order_sn']), 'remove', 'scm_rectify_order');	
	    $db->query("DELETE FROM " . $os->table('scm_rectify_goods') . " WHERE order_id='$order_id'");   
    }

    /* 清除缓存 */
    clear_cache_files();
    
	if($_REQUEST['is_ajax']==1){
    	$url = 'scm_depot.php?act=query_rectify_order&' . str_replace('act=remove_rectify_order', '', $_SERVER['QUERY_STRING']);
	}else{
		$url = 'scm_depot.php?act=list_rectify_order';
	}
    os_header("Location: $url\n");
    exit;	
}

elseif($_REQUEST['act']=='operate_rectify_order'){
    if (empty($_POST['order_id']))
    {
        sys_msg('invalid param');
    }	
    $order_id = intval($_POST['order_id']);
    $order = scm_rectify_order_info($order_id);
    if(empty($order)){
    	sys_msg('仓储调整单不存在');
    }
    
    $action_note = empty($_POST['action_note']) ? '' : trim($_POST['action_note']);

    if (isset($_POST['confirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法确认通过');
    	}
        $operation      = 'order_status';
        $order_status   = 1;
    }

    if (isset($_POST['rectify']))
    {
        if($order['order_status'] <> 1 && $order['order_status'] <> 3){
    		sys_msg('无效状态无法调整库存');
    	}
	    if(FALSE===alter_storage('rectify', $order_id)){
    		sys_msg('调整库存失败');exit;
    	}
        $operation      = 'order_status';
        $order_status   = 2;
    } 

    if (isset($_POST['rollback']))
    {
        if($order['order_status'] <> 2){
    		sys_msg('无效状态无法回滚库存');
    	}
	    if(FALSE===alter_storage('rectify', $order_id, false)){
    		sys_msg('回滚库存失败');exit;
    	}
        $operation      = 'order_status';
        $order_status   = 3;
    } 
     
    if (isset($_POST['finish']))
    {
        if($order['order_status'] <> 2 && $order['order_status'] <> 3){
    		sys_msg('无效状态无法完成');
    	}
        $operation      = 'order_status';
        $order_status   = 5;
    }       
   
    if (isset($_POST['disaffirm']))
    {
        if($order['order_status'] <> 0){
    		sys_msg('无效状态无法作废');
    	}
        $operation      = 'order_status';
        $order_status   = 4;
    }
    update_scm_order('rectify', $order_id, array($operation => $order_status));
	update_scm_order_action('rectify', $order['order_sn'], $order_status, $action_note);
    os_header("Location: scm_depot.php?act=info_rectify_order&id=$order_id");
    exit;
}

elseif ($_REQUEST['act'] == 'search_goods'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    $json = new JSON();
    
    $keyword = empty($_GET['keyword']) ? '' : json_str_iconv(trim($_GET['keyword']));

    $result = array('error'=>0, 'message'=>'', 'content'=>'');
    
    $sql = "SELECT g.goods_id,g.goods_name,g.goods_sn FROM " . $os->table('goods') . " g WHERE " . 
           "g.is_delete=0 AND (g.goods_id LIKE '%" . mysql_like_quote($keyword) . "%' OR g.goods_name " . 
           " LIKE '%" . mysql_like_quote($keyword) . "%'" . " OR g.goods_sn LIKE '%" . mysql_like_quote($keyword) . 
           "%')";
    $res = $db->query($sql);
    $result['goodslist'] = array();
    while ($row = $db->fetchRow($res))
    {
        $result['goodslist'][] = array('goods_id' => $row['goods_id'], 'name' => $row['goods_id'] . '  ' . $row['goods_name'] . '  ' . $row['goods_sn']);
    }
    die($json->encode($result));
}

elseif($_REQUEST['act']=='dump_order_goods'){
     if (empty($_GET['order_id']) || !in_array($_GET['type'], array('check', 'rectify')))
    {
        sys_msg('invalid param');
    }	
    $order_type   = trim($_GET['type']);
    $order_id     = intval($_GET['order_id']);
    $order        = get_fast_scm_order_info($order_type, $order_id);
    if(empty($order)){
    	sys_msg(fast_scm_order_ur($order_type).'不存在');
    } 

    @set_time_limit(0);
    
    include_once('includes/cls_phpzip.php');
    $zip = new PHPZip;

    /* 文件名称 */
    $temp_filename = fast_scm_order_ur($order_type).'['.$order['order_sn'].']商品_list';

    $content = '';
    if (OS_CHARSET != 'gbk')
    {
        $temp_filename = os_iconv('UTF8', 'GB2312', $temp_filename);
    }

    /* 文件标题 */
    if (OS_CHARSET != 'utf-8')
    {
        $content .= os_iconv(OS_CHARSET, 'utf-8', fast_scm_order_ur($order_type).'(单号:'.$order['order_sn'].')商品列表')."\n";
        /* 红包序列号, 红包金额, 类型名称(红包名称), 使用结束日期 */
        $content .= os_iconv(OS_CHARSET, 'utf-8', '商品编号') . "\t";
        $content .= os_iconv(OS_CHARSET, 'utf-8', '商品名称') . "\t";
        $content .= os_iconv(OS_CHARSET, 'utf-8', '商品颜色') . "\t";
        $content .= os_iconv(OS_CHARSET, 'utf-8', '商品尺码') . "\t";
        $content .= os_iconv(OS_CHARSET, 'utf-8', '商品价格') . "\t";
        $content .= os_iconv(OS_CHARSET, 'utf-8', '数量') . "\t";
        if($order_type=='rectify'){
        	$content .= os_iconv(OS_CHARSET, 'utf-8', '库存数') . "\t";
        	$content .= os_iconv(OS_CHARSET, 'utf-8', '盈亏数') . "\t";	
        }
        $content .= os_iconv(OS_CHARSET, 'utf-8', '小计') ."\n";
    }
    else
    {
        $content .= fast_scm_order_ur($order_type).'(单号:'. $order['order_sn'] .')商品列表'."\n";
        /* 红包序列号, 红包金额, 类型名称(红包名称), 使用结束日期 */
        $content .= '商品编号' . "\t";
        $content .= '商品名称' . "\t";
        $content .= '商品颜色' . "\t";
        $content .= '商品尺码' . "\t";
        $content .= '商品价格' . "\t";
        $content .= '数量' . "\t";
        if($order_type=='rectify'){
        	$content .= '库存数' . "\t";
        	$content .= '盈亏数' . "\t";        	
        }
        $content .= '小计' . "\n";
    }

    $temp_goods = array();
    $code_table = array();
    $temp_goods = temp_order_goods($order_type, $order_id);
    foreach ($temp_goods as $val){
        $content .= $val['goods_sn'] . "\t";
        if (!isset($code_table[$val['goods_name']]))
        {
            if (OS_CHARSET != 'utf-8')
            {
                $code_table[$val['goods_name']] = os_iconv(OS_CHARSET, 'utf-8', $val['goods_name']);
            }
            else
            {
                $code_table[$val['goods_name']] = $val['goods_name'];
            }
        }
        $content .= $code_table[$val['goods_name']] . "\t";
        $content .= $val['color_name'] . "\t";
        $content .= $val['size_name'] . "\t";        
        $content .= $val['actual_price'] . "\t";
        $content .= $val['goods_number'] . "\t";
        if($order_type=='rectify'){
	        $content .= $val['goods_number_inventory'] . "\t";
	        $content .= $val['goods_number_loss'] . "\t";	
        }
        if($order_type=='rectify'){
        	$content .= $val['loss_amount'];
        }else{
        	$content .= $val['actual_amount'];
        }
        $content .= "\n";
    }
    
    if (OS_CHARSET != 'utf-8')
    {
        $content = os_iconv(OS_CHARSET, 'utf-8', $content);
    }
    $zip->add_file("\xFF\xFE" . utf82u2($content), "$temp_filename.csv");

    header("Content-Disposition: attachment; filename=$temp_filename.zip");
    header("Content-Type: application/unknown");
    die($zip->file());	
}

elseif($_REQUEST['act']=='print_order_goods'){
	if(empty($_GET['order_id']))
    {
    	sys_msg('invalid param');
    }    
    $_REQUEST['type'] = 'check';
    $order_id     = intval($_GET['order_id']);
    $order        = scm_check_order_info($order_id);
    if(empty($order)){
		sys_msg('仓储盘点单不存在');
    }
    
    $smarty->assign('ur_here', '打印仓储盘点单商品');
    $smarty->assign('action_link', array('href' => 'scm.php?act=list_check_order', 'text' => '仓储盘点单列表'));	  
    $smarty->assign('full_page',     1);
	
    $list = get_order_goods_list();
    $smarty->assign('goods_list',          $list['goods']);    
    $smarty->assign('filter',              $list['filter']);
    $smarty->assign('page_count',          $list['page_count']); 
    $smarty->assign('record_count',        $list['record_count']);
             
    assign_query_info();
    $smarty->display('scm_order_goods_print.tpl');	
}

elseif($_REQUEST['act']=='get_goods_info'){
    include_once(ROOT_PATH . 'includes/cls_json.php');
    
    $goods_id = isset($_REQUEST['goods_id']) ? intval($_REQUEST['goods_id']) : 0;
    $order_id = isset($_REQUEST['order_id']) ? intval($_REQUEST['order_id']) : 0;
//    $order_type   = trim($_GET['type']);
    
    if (empty($goods_id))
    {
        make_json_response('', 1, '无法获取系列产品详细信息');
    }
//    $order = get_fast_scm_order_info($order_type, $order_id);
//    if(empty($order)){
//		make_json_error(fast_scm_order_ur($order_type).'不存在');
//    }
    
    $json = new JSON();
        
	/* 取得商品信息 */
	$sql = "SELECT g.goods_id, c.cat_name, g.goods_sn, g.goods_name, b.brand_name, " .
	       "g.goods_number, g.market_price, g.shop_price, g.promote_price, " .
	       "g.promote_start_date, g.promote_end_date, g.goods_brief, g.goods_type, g.is_promote " .
	       "FROM " . $os->table('goods') . " g LEFT JOIN " . $os->table('brand') . 
	       " b ON g.brand_id = b.brand_id LEFT JOIN " . $os->table('category') . 
	       " c ON g.cat_id = c.cat_id WHERE g.is_delete=0 AND g.goods_id = '$goods_id'";
	$goods = $db->getRow($sql);

	$goods['actual_price'] = price_format(abs($goods['shop_price']), false);        

	/* 取得商品属性 */
	$sql = "SELECT c.color_id c_id,c.color_name c_name,c.img_file AS img_url,'color' AS c_type FROM " . 
		   $os->table('goods_color') . " gc LEFT JOIN " . $os->table('color') . 
	       " c ON c.color_id=gc.color_id WHERE gc.goods_id=$goods_id UNION " . 
	       "SELECT s.size_id c_id,s.size_name c_name,'' AS img_url,'size' AS c_type FROM " . 
	       $os->table('goods_size') . " gs LEFT JOIN " . $os->table('size') . 
	       " s ON gs.size_id=s.size_id WHERE gs.goods_id=$goods_id";
	$attr_list = $db->getAll($sql);	
	$goods['attr_list'] = $attr_list;	
	echo $json->encode($goods);	
}
?>